package com.gxzy.util.wx;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 微信配置工具类
 */

@Component
@ConfigurationProperties(prefix = "mconfig.wx")
@Data
public class WxCfgUtil {
    private String accessToken;
    private String accessTokenExpiresIn;

    private String jsapiTicket;
    private String jsapiTicketExpiresIn;

    private String appid;
    private String secret;

    /**
     * 获取请求access_token信息接口
     *
     * @return String
     */
    public String getUrlAccessToken() {
        return "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
    }

    /**
     * 获得jsapi_ticket（有效期7200秒，开发者必须在自己的服务全局缓存jsapi_ticket）：
     *
     * @return String
     */
    public String getUrlTicketJSAPI() {
        return "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
    }


    /**
     * 创建JSAPI签名信息
     *
     * @param noncestr  随机字符串
     * @param timestamp 时间戳： 秒
     * @param url       请求路径
     * @return String
     */
    public String signJSAPI(String noncestr, String timestamp, String url) {
        String string = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
        System.out.println("sign before -> " + string);
        return sha1(string);
    }

    /**
     * SHA1签名
     *
     * @param decript 待签名信息
     * @return String
     */
    private String sha1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuilder hexString = new StringBuilder();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
